package com.xcc.dataStructures.demo04_stack;

import java.util.Scanner;

/**
 * 模拟栈
 *
 * @author xiaocheng
 * @date 2020/11/25 10:19
 */
public class StackDemo {

    public static void main(String[] args) {
        Stack stack = new Stack(4);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("=========================");
            System.out.println("a[push]往栈中添加数据");
            System.out.println("g[pop]从栈中取数据");
            System.out.println("s[show]打印栈");
            System.out.println("e[exit]退出");
            System.out.println("请输入想要执行的操作:");
            switch (scanner.next()) {
                case "a":
                    System.out.println("输入添加的元素:");
                    stack.push(scanner.nextInt());
                    break;
                case "g":
                    try {
                        System.out.printf("获取的元素 %d\n", stack.pop());
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }
                    break;
                case "s":
                    stack.show();
                    break;
                case "e":
                    return;
            }
        }
    }

}

class Stack {

    private int maxSize;
    private int[] arr;
    private int top = -1;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    /**
     * 往栈中push数据
     */
    public void push(int val) {
        if (isFull()) {
            System.out.println("栈满了，无法插入数据!");
            return;
        }
        arr[++top] = val;
    }

    /**
     * 判断满
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 获取
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空了，无法取到数据");
        }
        return arr[top--];
    }

    /**
     * 打印栈
     */
    public void show() {
        for (int i = top; i >= 0; i--) {
            System.out.printf("arr[%d] = %d\n", i, arr[i]);
        }
    }

    /**
     * 判空
     */
    public boolean isEmpty() {
        return top < 0;
    }

}